package controller.bullets
{
	import away3d.bounds.NullBounds;
	import away3d.containers.ObjectContainer3D;
	import away3d.core.math.Quaternion;
	
	import controller.GameControllerBase;
	import controller.MainWeaponController;
	
	import flash.display.BitmapData;
	import flash.events.TimerEvent;
	import flash.geom.Matrix3D;
	import flash.geom.Vector3D;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import gameObject.GameObjectBase;
	import gameObject.SingleBullet;
	import gameObject.resources3D.BulletResource;
	
	import net.P2p;
	
	public class StraightBullet extends BullectControllerBase
	{
		private var _timer:Timer = new Timer(17);
		private var _speed:Number;
		private var _range:Number;
		private var _currentRange:Number=0;
		
		private var _mainWepCon:MainWeaponController;
		private var _currentID:uint;
		
		public function StraightBullet()
		{
			super();
		}
		
		override public function setup(target:SingleBullet):void
		{
			super.setup(target);
			
			var _bullet:SingleBullet = target as SingleBullet;
			var _bulletRes:BulletResource = _bullet.resource as BulletResource;
			
			_speed = _bulletRes.speed;
			_range = _bulletRes.range;
		}
		
		override public function dispose():void
		{
			_target.controller = null;
		}
		
		override public function fire():void
		{
			super.fire();
			_timer.start();
			_timer.addEventListener(TimerEvent.TIMER,onTimer);
		}
		
		private function onTimer(e:TimerEvent):void
		{
			e.updateAfterEvent();//听说在timer事件上加个这个有好处，不知道是不是真的
			
			_currentRange+=_speed;
			_target.controller.instObj.moveBackward(_speed);
			
			if(_currentRange>=_range)
			{
				remove();
			}else
			{
				var nextX:Number = _target.controller.instObj.scenePosition.x;
				var nextY:Number =  _target.controller.instObj.scenePosition.z;
				var px:Number = CollisionWorld.mapScaleX*(CollisionWorld.hitStartX+nextX);
				var py:Number = CollisionWorld.mapScaleY*(CollisionWorld.hitStartY-nextY);
				
				if(buildingHitTest(px,py) == false)
				{
					_target.moveBackward(_speed);
					//trace("咻");
				}else
				{
					remove();
				}
			}
		}
		
		private function buildingHitTest(X:Number,Y:Number):Boolean
		{
			var mapData:BitmapData = CollisionWorld.collisionMap.bitmapData;
			var p:uint = mapData.getPixel(X,Y);
			
			if(p>0xffff)return true
			else return false;
		}
		
		private function remove():void
		{
			_timer.stop();
			_timer.removeEventListener(TimerEvent.TIMER,onTimer);
			
			//trace("砰~");
			
			if(_target.parent)_target.parent.removeChild(_target);
			dispose();
		}
		
	}
}